/**
 * 
 */
package com.wsj.web.action.admin.batchImportNews;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.wsj.service.batchmanagenews.IBatchUploadNews;
import com.wsj.web.form.admin.batchImportNews.ImportNewsForm;

/**
 * @author fengbin  createTime:2009-10-12
 * 批量导入新闻
 */
public class ImportNewsAction extends Action{

	
	private IBatchUploadNews  batchUploadNews;
	
	
	
	public IBatchUploadNews getBatchUploadNews() {
		return batchUploadNews;
	}



	public void setBatchUploadNews(IBatchUploadNews batchUploadNews) {
		this.batchUploadNews = batchUploadNews;
	}



	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		ImportNewsForm importNewsForm = (ImportNewsForm)form;
		FormFile formfile =importNewsForm.getFile(); 
		if(formfile!=null){
			
			File newFile = getFileFromBytes(formfile.getFileData(),formfile.getFileName());
			batchUploadNews.uploadNews(newFile);
		}
		
		return mapping.findForward("importNewsResult");
		
	}
	
	
	
	  /** *//**
     * 把字节数组保存为一个文件
     * @Author Sean.guo
     * @EditTime 2007-8-13 上午11:45:56
     */
    public static File getFileFromBytes(byte[] b, String outputFile) {
        BufferedOutputStream stream = null;
        File file = null;
        try {
            file = new File(outputFile);
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }
}
